//
//  ActiviteDetailVC.m
//  KuWoCan
//
//  Created by hwd on 17/3/15.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "ActiviteDetailVC.h"
#import "ProsecutorCell.h"
#import "DoubleLabCell.h"
#import "BottomDoubleBtnView.h"
#import "ActiviteApplyVC.h"
#import "NWSaleApplyRequest.h"
#import "SADetailModel.h"
#import "CargoCell.h"
#import "PhotoManageCell.h"
#import "NWPicManageRequest.h"
#import "PicPageListModel.h"

@interface ActiviteDetailVC ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
{
    dispatch_semaphore_t semaphore;
    BottomDoubleBtnView *btnsView;
}

@property (nonatomic,strong) NSArray *detailInfoArr; //活动详情字典

@property (nonatomic,strong) NSMutableArray<SADetailCargoModel *> *cargoListArr;  //商品数组

@property (nonatomic,strong) NSMutableArray *recordListArr; //审批信息数组

@property (nonatomic,strong) SADetailInfoModel *detailInfoModel;

@property (nonatomic,strong) UITableView *tabView;

@property (nonatomic,strong) UIAlertView *deleteAlert;

@property (nonatomic,strong) NSMutableArray<PicListModel *> *pics1; //图片数组

@property (nonatomic,strong) NSMutableArray<PicListModel *> *pics2; //图片数组

@property (nonatomic,assign) SAQueryStatus orderStatus;

@property (nonatomic,assign)BOOL isNeedHXBZ;//是否需要核销标准
@property (nonatomic,assign)BOOL isShowHXBZ;//是否展示核销标准
@property (nonatomic,strong)NSMutableArray *DataHXBZArr;
@property (nonatomic,assign)NSInteger tagNumber;
@property (nonatomic,strong)NSString *mbContect;//核销标准的内容
@property (nonatomic,strong)UIButton *deleteBtn;


@end

@implementation ActiviteDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    if (self.moduleType == HomeModuleTypeSA) {
        self.title = @"促销活动";
    } else {
        self.title = @"促销活动核销";
    }
    _tagNumber = 0;
    [self getData];
}

- (void)startRequestTable
{
    NWSaleApplyRequest *request = [[NWSaleApplyRequest alloc] init];
    if (_moduleType == HomeModuleTypeSA)
    {
        [request startRequestSaleApplyDetailWithId:_orderId];
    }
    else
    {
        [request startRequestSaleCheckDetailWithId:_orderId];
    }
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        NSLog(@"%@",result);
        if (succ)
        {
//            NSLog(@"approvalStatus========%@",result[@"kwPromotionApplication"][@"approvalStatus"]);
            //这里做数据解析
            SADetailModel *model = [[SADetailModel alloc] initWithDictionary:result error:nil];
            if (_moduleType == HomeModuleTypeSA)
            {
                _detailInfoModel = [[SADetailInfoModel alloc] initWithDictionary:result[@"kwPromotionApplication"] error:nil];
            }
            else
            {
                _detailInfoModel = [[SADetailInfoModel alloc] initWithDictionary:result[@"kwPromotionExamine"] error:nil];
            }
            _cargoListArr = model.itemList;
            _recordListArr = [SADetailRecordModel arrayOfModelsFromDictionaries:model.recordList];
            
            _detailInfoArr = @[
  @{@"促销活动名称":[ToolViewViewController GetDataStr:_detailInfoModel.name]},
  @{@"活动目的":[ToolViewViewController GetDataStr:_detailInfoModel.objective]},
  @{@"执行城市":[ToolViewViewController GetDataStr:_detailInfoModel.city]},
  @{@"执行范围":[ToolViewViewController GetDataStr:_detailInfoModel.ranges]},
  @{@"执行时间": [ToolViewViewController GetDataStr:_detailInfoModel.executionTime]},
  @{@"内容及形式":[ToolViewViewController GetDataStr:_detailInfoModel.content]},
  @{@"物料":[ToolViewViewController GetDataStr:_detailInfoModel.materiel]},
  @{@"费用总计":[ToolViewViewController GetDataStr:_detailInfoModel.totalExpenses]},
  @{@"销售额":[ToolViewViewController GetDataStr:_detailInfoModel.salesVolume]},
  @{@"费效比率":[ToolViewViewController GetDataStr:_detailInfoModel.ratio]},
  @{@"期间销售额" :[ToolViewViewController GetDataStr:_detailInfoModel.activitySales]},
  @{@"期间费效比率" : [ToolViewViewController GetDataStr:_detailInfoModel.activityRatio]}];
            
            if (_moduleType == HomeModuleTypeSA)
            {
                _orderStatus = [_detailInfoModel.approvalStatus integerValue];

            }
            else
            {
                _orderStatus = [_detailInfoModel.examineStatus integerValue];
            }

            
            if ([_detailInfoModel.approverUser isEqualToString:[Singleton shareInstance].userId] && _moduleType == HomeModuleTypeSA)//选择核销标准
            {
                _isNeedHXBZ = _orderStatus == SAQueryStatusToAudit?YES:NO;
            }
         
                if (_moduleType == HomeModuleTypeSA) {
                    _isShowHXBZ = result[@"kwPromotionApplication"][@"mbContent"]?YES:NO;
                    _mbContect = result[@"kwPromotionApplication"][@"mbContent"]?result[@"kwPromotionApplication"][@"mbContent"]:@"未填写";
                }else
                {
                    _isShowHXBZ = result[@"kwPromotionExamine"][@"mbContent"]?YES:NO;
                    _mbContect = result[@"kwPromotionExamine"][@"mbContent"]?result[@"kwPromotionExamine"][@"mbContent"]:@"未填写";
                }
                
            
            
        } else {
            [SVProgressHUD showErrorWithStatus:message];
        }
        dispatch_semaphore_signal(semaphore);
    }];

}

- (void)reloadData {
    NWSaleApplyRequest *request = [[NWSaleApplyRequest alloc] init];
    if (_moduleType == HomeModuleTypeSA)
    {
        [request startRequestSaleApplyDetailWithId:_orderId];
    }
    else
    {
        [request startRequestSaleCheckDetailWithId:_orderId];
    }
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            //这里做数据解析
            SADetailModel *model = [[SADetailModel alloc] initWithDictionary:result error:nil];
            if (_moduleType == HomeModuleTypeSA)
            {
                _detailInfoModel = [[SADetailInfoModel alloc] initWithDictionary:result[@"kwPromotionApplication"] error:nil];
            }
            else
            {
                _detailInfoModel = [[SADetailInfoModel alloc] initWithDictionary:result[@"kwPromotionExamine"] error:nil];
            }
            _cargoListArr = model.itemList;
            _recordListArr = [SADetailRecordModel arrayOfModelsFromDictionaries:model.recordList];
            _detailInfoArr = @[
  @{@"促销活动名称":_detailInfoModel.name},
  @{@"活动目的":_detailInfoModel.objective},
  @{@"执行城市":_detailInfoModel.city},
  @{@"执行范围":_detailInfoModel.ranges},
  @{@"执行时间": _detailInfoModel.executionTime},
  @{@"内容及形式": _detailInfoModel.content ?: @""},
  @{@"物料":_detailInfoModel.materiel},
  @{@"费用总计":_detailInfoModel.totalExpenses},
  @{@"销售额":_detailInfoModel.salesVolume},
  @{@"费效比率": _detailInfoModel.ratio}/**,@{@"提报人": _detailInfoModel.user.name}**/];

            if (_moduleType == HomeModuleTypeSA)
            {
                _orderStatus = [_detailInfoModel.approvalStatus integerValue];
            }
            else
            {
                _orderStatus = [_detailInfoModel.examineStatus integerValue];
            }
            if ([_detailInfoModel.approverUser isEqualToString:[Singleton shareInstance].userId] && _moduleType == HomeModuleTypeSA)//选择核销标准
            {
                _isNeedHXBZ = _orderStatus == SAQueryStatusToAudit?YES:NO;
            }
         
            if (_moduleType == HomeModuleTypeSA) {
                    _isShowHXBZ = result[@"kwPromotionApplication"][@"mbContent"]?YES:NO;
                    _mbContect = result[@"kwPromotionApplication"][@"mbContent"]?result[@"kwPromotionApplication"][@"mbContent"]:@"未填写";
                }else
                {
                    _isShowHXBZ = result[@"kwPromotionExamine"][@"mbContent"]?YES:NO;
                    _mbContect = result[@"kwPromotionExamine"][@"mbContent"]?result[@"kwPromotionExamine"][@"mbContent"]:@"未填写";
                }

            [self.tabView reloadData];

        } else {
            [SVProgressHUD showErrorWithStatus:message];
        }
    }];
}

- (void)startRequestPic1
{
    NWPicManageRequest *picRequest = [[NWPicManageRequest alloc] init];
    [picRequest startRequestQueryPicWithProcessId:_orderId pageNo:@"1" pageSize:@"3" type:[NSString stringWithFormat:@"%ld",(long)PicTypeSCSite]];
    [picRequest completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            if(!_pics1)
            {
                _pics1 = [NSMutableArray array];
            }
            PicPageListModel *pageModel = [[PicPageListModel alloc] initWithDictionary:result[@"pageList"] error:nil];
            if ([pageModel.count integerValue] > 0)
            {
                _pics1 = pageModel.list.mutableCopy;
            }
            dispatch_semaphore_signal(semaphore);
        }
        
        
    }];
}

- (void)startRequestPic2
{
    NWPicManageRequest *picRequest2 = [[NWPicManageRequest alloc] init];
    [picRequest2 startRequestQueryPicWithProcessId:_orderId pageNo:@"1" pageSize:@"3" type:[NSString stringWithFormat:@"%ld",(long)PicTypeSCBill]];
    [picRequest2 completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            if(!_pics2)
            {
                _pics2 = [NSMutableArray array];
            }
            PicPageListModel *pageModel = [[PicPageListModel alloc] initWithDictionary:result[@"pageList"] error:nil];;
            if ([pageModel.count integerValue] > 0)
            {
                _pics2 = pageModel.list.mutableCopy;
            }
            dispatch_semaphore_signal(semaphore);
        }
    }];
}

- (void)getData
{
    // 创建信号量
    semaphore = dispatch_semaphore_create(0);
    // 创建全局并行
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        [self startRequestTable];
    });
    
    if (_moduleType == HomeModuleTypeSC)
    {
        dispatch_group_async(group, queue, ^{
            
            [self startRequestPic1];
        });
        dispatch_group_async(group, queue, ^{
            
            [self startRequestPic2];
        });
    }
    
    //等待3个请求完成后,创建UI
    dispatch_group_notify(group, queue, ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        if (_moduleType == HomeModuleTypeSC)
        {
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }
        if(_isNeedHXBZ){
            [self addGetHeXiaoMessage];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setUpUI];
            });
        }
       
    });
}
-(void)addGetHeXiaoMessage//有权限审批 且 待审批状态
{
    //1 进场费  2 陈列费  3 促销活动
    [HttpRequest PostrequestUrl:[NSString stringWithFormat:@"%@/jeesite/interface/kwMoban/list",baseUrlMe] Dic:@{@"mbType":@"3"} completion:^(NSDictionary *responseDic) {
        if ([responseDic[@"success"] boolValue]){
            _DataHXBZArr = [[NSMutableArray alloc]initWithArray:responseDic[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setUpUI];
            });
        }else
        {
            [ToolViewViewController addPopAlterViewController:responseDic[@"msg"]?responseDic[@"msg"]:@"" Controller:self];
        }
    }];
}
//活动目的这一项,将数字装换成中文字符
- (NSString *)getObjects
{
    NSArray *goalArr = [_detailInfoModel.objective componentsSeparatedByString:@","];
    NSMutableArray *goalStrArr = [NSMutableArray array];
    for (NSString *obj in goalArr)
    {
        NSString *str = [Constants getActiviteGoalStrWithNumberStr:obj];
        [goalStrArr addObject:str];
    }
    NSString *goalsStr = [goalStrArr componentsJoinedByString:@","];
    return goalsStr;
}

//修改按钮,先判断是否是自己的订单
//如果是自己订单,待提交  待审批状态下  有修改按钮
- (void)createChangeBtn
{
    if ([[Singleton shareInstance].userType integerValue] == UserTypeAgency)
    {
        if ([_detailInfoModel.user.id isEqualToString:[Singleton shareInstance].userId])
        {
            if (_orderStatus == SAQueryStatusToSubmit || _orderStatus == SAQueryStatusToAudit)
            {
                [self createRightButton:@"修改" selector:@selector(changeInfo)];
            }
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)changeInfo
{
    ActiviteApplyVC *vc = [[ActiviteApplyVC alloc] init];
    vc.isChangeInfo = YES;
    vc.detailInfoModel = _detailInfoModel;
    vc.cargoListArr = _cargoListArr;
    vc.orderStatus = [NSString stringWithFormat:@"%ld",(long)_orderStatus];
    vc.orderId = _orderId;
    vc.moduleType = _moduleType;
    vc.sitePhotoArr = _pics1;
    vc.paperPhotoArr = _pics2;
    vc.isShowHXBZ = _isShowHXBZ;
    vc.mbContect = _mbContect;
    __weak typeof(self) weakSelf = self;
    vc.reloadBlock = ^{
        [self reloadData];
    };
    vc.picHandle = ^(NSArray<PicListModel *> *sitePicArr, NSArray<PicListModel *> *paperPicArr) {
        _pics1 = sitePicArr.mutableCopy;
        _pics2 = paperPicArr.mutableCopy;
        [weakSelf.tabView reloadData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)createBottomView
{
    //这里创建底部操作按钮,先要判断是否是本人的订单,如果是在判断自己的身份,显示对应按钮
    //是本人订单
    //根据订单状态来显示底部按钮
    if ([[Singleton shareInstance].userType integerValue] == UserTypeAgency)
    {
        if ([_detailInfoModel.user.id isEqualToString:[Singleton shareInstance].userId])
        {
            if (_moduleType == HomeModuleTypeSA)
            {
                if (_orderStatus == SAQueryStatusToAudit || _orderStatus == SAQueryStatusToSubmit)
                {
                    [self createBottomBtnWithTitle:@"删除"];
                }
                else if (_orderStatus == SAQueryStatusCompleted)
                {
                    [self createBottomBtnWithTitle:@"确认查看"];
                }
                else
                {
                    [_tabView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.bottom.equalTo(@0);
                    }];
                }
            }
            else if (_moduleType == HomeModuleTypeSC)
            {
                if (_orderStatus == SAQueryStatusToSubmit) {
                    [self createSubmitButton];
                } else {
                    [_tabView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.bottom.equalTo(@0);
                    }];
                }
            }
            
        }
    }
    else
    {
        if ([_detailInfoModel.approverUser isEqualToString:[Singleton shareInstance].userId])
        {
            if(_orderStatus == SAQueryStatusToAudit)
            {
                [self createDoubleBtnsView];
            }
            else if (_orderStatus == SAQueryStatusAuditting || _orderStatus == SAQueryStatusPlanningDepartment || _orderStatus == SAQueryStatusMarketingCenter)
            {
                [self createDoubleBtnsView];
            }
            else
            {
                [_tabView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(@0);
                }];
            }
        }
        else
        {
            [_tabView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(@0);
            }];
        }
    }
}

- (void)createBottomBtnWithTitle:(NSString *)title
{
    _deleteBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_deleteBtn setBackgroundColor:KwBlueColor];
    [_deleteBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_deleteBtn setTitle:title forState:UIControlStateNormal];
    _deleteBtn.titleLabel.font = KwFont(16.0);
    [_deleteBtn addTarget:self action:@selector(deleteOrder:) forControlEvents:UIControlEventTouchUpInside];
    _deleteBtn.layer.masksToBounds = YES;
    _deleteBtn.layer.cornerRadius = 5.0;
    [self.view addSubview:_deleteBtn];
    [_deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@-5);
        make.top.equalTo(_tabView.mas_bottom).offset(1);
        make.left.equalTo(@5);
        make.right.equalTo(@-5);
    }];
}

- (void)createSubmitButton {
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [confirmBtn setBackgroundColor:KwBlueColor];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmBtn setTitle:@"提交" forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = KwFont(16.0);
    [confirmBtn addTarget:self action:@selector(submitOrder) forControlEvents:UIControlEventTouchUpInside];
    confirmBtn.layer.masksToBounds = YES;
    confirmBtn.layer.cornerRadius = 5.0;
    [self.view addSubview:confirmBtn];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@-5);
        make.top.equalTo(_tabView.mas_bottom).offset(1);
        make.left.equalTo(@5);
        make.right.equalTo(@-5);
    }];
}

- (void)createDoubleBtnsView
{
    //拒绝  通过
    btnsView = [[BottomDoubleBtnView alloc] init];
    btnsView.orderId = _orderId;
    btnsView.orderStatus = [NSString stringWithFormat:@"%zd",_orderStatus];
    btnsView.moduleType = _moduleType;
    btnsView.mbContent =_DataHXBZArr.count>=_tagNumber+1?(_DataHXBZArr[_tagNumber][@"contents"]?_DataHXBZArr[_tagNumber][@"contents"]:@""):@"";
    [self.view addSubview:btnsView];
    [btnsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@-5);
        make.height.equalTo(@50);
        make.left.equalTo(@5);
        make.right.equalTo(@-5);
    }];
}

- (void)deleteOrder:(UIButton *)btn
{
    if ([btn.titleLabel.text isEqualToString:@"确认查看"]) {
        [HttpRequest PostrequestUrl:[NSString stringWithFormat:@"%@/jeesite/interface/promotionA/userConfirm",baseUrlMe] Dic:@{@"id":[ToolViewViewController isNotNullStr:_orderId]?_orderId:@"",@"approvalStatus":@"6"} completion:^(NSDictionary *responseDic) {
            if ([responseDic[@"success"] boolValue]) {
                [_deleteBtn removeFromSuperview];
                [self getData];
            }else
            {
                [SVProgressHUD showErrorWithStatus:@"确认失败"];
            }
           
            
        }];
    }else
    {
        _deleteAlert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确定删除？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [_deleteAlert show];

    }
}

- (void)submitOrder {
    NWSaleApplyRequest *request = [[NWSaleApplyRequest alloc] init];

    [request startRequestPassApplyOrCheckWithId:_orderId userId:[Singleton shareInstance].userId approvalStatus:[NSString stringWithFormat:@"%zd", _orderStatus] approvalType:@"0" approvalMemo:@"" moduleType:_moduleType MbContent:_mbContect?_mbContect:@""];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ) {
            [SVProgressHUD showSuccessWithStatus:@"提交成功"];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [SVProgressHUD showErrorWithStatus:message];
        }
    }];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView == _deleteAlert)
    {
        if (buttonIndex == 1)
        {
            NWSaleApplyRequest *request = [[NWSaleApplyRequest alloc] init];
           [request startRequestDeleteApplyOrCheckWithId:_orderId moduleType:_moduleType];
            [request completion:^(id result, NSString *message, id extension, BOOL succ) {
                if (succ)
                {
                    [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }];
        }
    }
}

- (void)setUpUI
{
    [self createChangeBtn];
    
    //创建列表
    _tabView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
    _tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tabView.estimatedRowHeight = 40.0;
    _tabView.rowHeight = UITableViewAutomaticDimension;
    _tabView.delegate = self;
    _tabView.dataSource = self;
    [self.view addSubview:_tabView];
    [_tabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@-55);
    }];
    
    [self createBottomView];
}

#pragma mark tableViewDelegate,DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_moduleType == HomeModuleTypeSA)
    {
        if (_isNeedHXBZ || _isShowHXBZ) {
            return 4;
        }
        return 3;
    }
    else 
    {
        if (_isNeedHXBZ || _isShowHXBZ) {
            return 6;
        }
        return 5;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        if ([_detailInfoModel.approvalType integerValue] == 1) {
            return _recordListArr.count + 1;
        }
        return _recordListArr.count;
    }
    else if(section == 1)
    {
        return _detailInfoArr.count;
    }
    else if(section == 2)
    {
        return _cargoListArr.count;
    }
    else if(section == 3 && _isNeedHXBZ)//选择核销标准
    {
        return 2;
    }
    else if(section == 3 && _isShowHXBZ && _moduleType == HomeModuleTypeSA)//展示核销标准
    {
        return 1;
    }
    else if(section == 5 && _isShowHXBZ && _moduleType == HomeModuleTypeSC)//展示核销标准
    {
        return 1;
    }
    else
    {
        if (_moduleType == HomeModuleTypeSA)
        {
            return 0;
        }
        else
        {
            return 1;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_moduleType == HomeModuleTypeSA)
    {
        if (section == 0) {
            return _recordListArr.count > 0 ? 50 : 0.0000001;
        } else if(section == 3 && _isNeedHXBZ)
        {
            return 0.0000001;
        }
        return 50;
    }
    else
    {
        if (section == 3 || section == 4)
        {
            return 10;
        } else if (section == 0) {
            return _recordListArr.count > 0 ? 50 : 0.0000001;
        }
        else
        {
            return 50;
        }
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        UIView *headView = [self createHeaderViewWithTitle:@"审批信息"];
        return _recordListArr.count > 0 ? headView : [UIView new];
    }
    else if(section == 1)
    {
        UIView *headView = [self createHeaderViewWithTitle:@"活动详情"];
        return headView;
    }
    else if(section == 2)
    {
        UIView *headView = [self createHeaderViewWithTitle:@"产品清单"];
        return headView;
    }
    else if((section == 3 && _isShowHXBZ &&  _moduleType == HomeModuleTypeSA) || (section == 5 && _isShowHXBZ &&  _moduleType == HomeModuleTypeSC))
    {
        UIView *headView = [self createHeaderViewWithTitle:@"费用核销标准"];
        return headView;
    }
    else
    {
        return nil;
    }
}

- (UIView *)createHeaderViewWithTitle:(NSString *)title
{
    UIView *headView = [UIView new];
    headView.backgroundColor = [UIColor whiteColor];
    UILabel *lab = [UILabel new];
    lab.text = title;
    lab.textColor = [UIColor blackColor];
    lab.font = KwFont(15);
    [headView addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headView.mas_left).offset(20);
        make.top.equalTo(headView.mas_top).offset(15);
        make.height.equalTo(@15);
    }];
    
    UIView *lineView = [UIView new];
    lineView.frame = CGRectMake(0, 50, self.view.bounds.size.width, 1.5);
    lineView.backgroundColor = KwGaryColor;
    [headView addSubview:lineView];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.0001;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *recordCell_ID = @"recordCellID";
    static NSString *doubleLabCell_ID = @"DoubleLabCell";
    static NSString *cargoCell_ID = @"CargoCell";
    static NSString *photoManageCell_ID = @"PhotoManageTCell";
    
    if (indexPath.section == 0)
    {

        if (indexPath.row == _recordListArr.count) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"refuseCell"];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"refuseCell"];
            }
            cell.textLabel.text = [NSString stringWithFormat:@"拒绝原因：%@", _detailInfoModel.approvalMemo];
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.font = KwFont(14);
            cell.textLabel.textColor = [UIColor grayColor];
            return cell;
        }

        
        UITableViewCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:recordCell_ID];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:recordCell_ID];
        }
        for (UIView *view in cell.contentView.subviews) {
            [view removeFromSuperview];
        }
        if (_recordListArr && _recordListArr.count > 0)
        {
            SADetailRecordModel *model = _recordListArr[indexPath.row];

            UILabel *firstLab = [UILabel new];
            firstLab.textColor = [UIColor grayColor];
            firstLab.font = [UIFont systemFontOfSize:14.0];
            firstLab.textAlignment = NSTextAlignmentLeft;
            firstLab.text = [NSString stringWithFormat:@"%@,%@,%@",model.user.name,model.approvalTime,model.approvalMemo];
            [cell.contentView addSubview:firstLab];
            [firstLab mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(@20);
                make.height.equalTo(@25);
                make.top.equalTo(@10);
                make.bottom.equalTo(@-15);
            }];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if(indexPath.section == 1)
    {
        DoubleLabCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:doubleLabCell_ID];
        if (!cell)
        {
            cell = [[DoubleLabCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:doubleLabCell_ID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        NSDictionary *dic = _detailInfoArr[indexPath.row];
        NSString *keyStr = [dic allKeys][0];
        cell.constStr = keyStr;
        
        if ([keyStr isEqualToString:@"活动目的"])
        {
             NSString *goalsStr = [self getObjects];
            cell.paraStr = goalsStr;
        }
       else
       {
            cell.paraStr = [dic objectForKey:keyStr];
       }
        return cell;
    }
    else if(indexPath.section == 2)
    {
        CargoCell *cell;
        //其余为商品展示
        cell = [tableView dequeueReusableCellWithIdentifier:cargoCell_ID];
        if (!cell)
        {
            cell = [[CargoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cargoCell_ID];
        }
        if (_cargoListArr.count > 0)
        {
            cell.saCargoModel = _cargoListArr[indexPath.row];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if(indexPath.section == 3 && _isNeedHXBZ &&  _moduleType == HomeModuleTypeSA)
    {
        if (indexPath.row == 0) {
            ChooseViewCell *cell;
            cell = [tableView dequeueReusableCellWithIdentifier:@"cellText"];
            if (!cell)
            {
                cell = [[ChooseViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellText"];
            }
            [cell setUpUIWithArr:_DataHXBZArr TextStr:@"" ChooseNumber:_tagNumber];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.reloadBtnBlock = ^(NSInteger tagNumber){

                _tagNumber = tagNumber-100;
        
                NSIndexSet *indeSec = [NSIndexSet indexSetWithIndex:3];
                [_tabView reloadSections:indeSec withRowAnimation:UITableViewRowAnimationAutomatic];
                
                [_tabView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:3] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
                
            };
            return cell;
        }else
        {
            TextViewCell *cell;
            cell = [tableView dequeueReusableCellWithIdentifier:@"cellText2"];
            if (!cell)
            {
                cell = [[TextViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellText2"];
            }
            [cell setUpUIWithTextStr:_DataHXBZArr[_tagNumber][@"contents"]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            cell.reloadTextBlock = ^(UITextView *texView){
                
                [_DataHXBZArr[_tagNumber] setObject:texView.text forKey:@"contents"];
                btnsView.mbContent = _DataHXBZArr[_tagNumber][@"contents"];

//            [_DataHXBZArr[_tagNumber][@"contents"] setObject:texView.text forKey:@"contents"];
//            [_tabView reloadSections:[NSIndexSet indexSetWithIndex:3] withRowAnimation:UITableViewRowAnimationNone];
                
            };
            return cell;
        }
    }
    else if(indexPath.section == 3 && _isShowHXBZ &&  _moduleType == HomeModuleTypeSA)
    {

            TextViewCell *cell;
            cell = [tableView dequeueReusableCellWithIdentifier:@"cellText2"];
            if (!cell)
            {
                cell = [[TextViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellText2"];
            }
            [cell setUpUIWithTextStr:_mbContect];
            cell.textView.editable = NO;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
    }
    else if(indexPath.section == 5 && _isShowHXBZ &&  _moduleType == HomeModuleTypeSC)
    {
        
        TextViewCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:@"cellText2"];
        if (!cell)
        {
            cell = [[TextViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellText2"];
        }
        [cell setUpUIWithTextStr:_mbContect];
        cell.textView.editable = NO;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else
    {
        if (_moduleType == HomeModuleTypeSA)
        {
            return nil;
        }
        else
        {
            PhotoManageCell *cell = [tableView dequeueReusableCellWithIdentifier:photoManageCell_ID];
            if (!cell)
            {
                cell = [[PhotoManageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:photoManageCell_ID];
            }

            cell.vc = self;
            if (indexPath.section == 3)
            {
                cell.titleLabel.text = @"活动现场照片管理";
                [cell configCell:_pics1];
                cell.picType = PicTypeSCSite;
            }
            else
            {
                cell.titleLabel.text = @"票据照片管理";
                [cell configCell:_pics2];
                cell.picType = PicTypeSCBill;
            }
            cell.orderId = _orderId;
            return cell;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)onTapLeftBarButton {
    [Singleton shareInstance].noRefresh = YES;
    [self.navigationController popViewControllerAnimated:YES];
}

@end
